#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author:Gwong Zaak Liu
@interpreter version:python 3.9.13
@file:  WhatIsTheWeather.py
@time:  2022/11
"""
import json
# import datetime
from fake_useragent import UserAgent
import requests
import logging
from loguru import logger


# 拼接cookies
def ConstructCookies():
    cookies = dict()
    cookies['Hm_lvt_9c221af010a163bdd2a5ae2cde8b62dc'] = "1608733420,1608733816,1608878511,1608991711"
    cookies['tianqiapi_uid'] = "37930"
    cookies['tianqiapi_uname'] = "kstephenlgz%40163.com"
    cookies['Hm_lpvt_9c221af010a163bdd2a5ae2cde8b62dc'] = "1608991757"
    cookies1 = json.dumps(cookies)
    # print(cookies1)
    cookies2 = cookies1.replace('{', '').replace('}', '').replace('\"', '').replace(': ', '=').replace(',', ';')
    # print(cookies2)
    return cookies2


"""
appid = "37583525"
appsecret = "d94eH7vz"
version = "v1"
cityid = "101280800"
"""


# 拼接URL
def ConstructURL():
    URL = dict()
    URL['interface'] = "https://tianqiapi.com/api?"
    URL['appid'] = "37583525"
    URL['appsecret'] = "d94eH7vz"
    URL['version'] = "v1"
    URL['cityid'] = "101280800"

    URLLink = json.dumps(URL).replace('{"interface": "', '').replace('}', '').replace('": "', '=').\
        replace('?", "', '?').replace('", "', '&').replace('"', '')
    return URLLink


def GetUrl(url):
    headers = {'User-Agent': UserAgent(verify_ssl=False).random,
               'Host': 'tianqiapi.com',
               'Referer': 'https://tianqiapi.com/index/doc?version=v1',
               'Cookies': ConstructCookies()}
    try:
        print('getting ' + url)
        r = requests.get(headers=headers, url=url, timeout=(5, 15))
        # 返回r.content为二进制内容
        # print(r.content)
        if r.status_code == 200:
            print(url + "is OK, got it")
            return r.content
        else:
            logging.info(url + '  get url err:' + r.status_code)
            return -1
    except requests.exceptions.Timeout as e:
        logging.info(e)
        print(e)
        return -1


def GetIt():
    # 目标网址
    logger.debug("GetIt ==>")
    Target_URL = ConstructURL()
    Reply = GetUrl(Target_URL)
    logger.debug("GetIt <==")
    return Reply


if __name__ == '__main__':
    print(GetIt())


